<template>
	<view>
		<!-- 顶部 -->
		<view style="width: 100%;height: 54px;position: relative;position: fixed;top: 0%;background-color: #f9f9f9;">
			<div style="position: absolute;top: 15px;left: 10px;" @click="returnHot()">
				<image src="../../static/icon/返回.png" style="height: 24px; width: 32px;"></image>
			</div>
			<view style="font-size: 18px;text-align: center;line-height:54px;font-weight: 500;">
				{{notation}}
			</view>
		</view>
		<div class="div1">
			<scroll-view class="chat-main" 
			 scroll-y="true" 
			 :scroll-into-view="scrollToView"
			 :scroll-with-animation="false">
				<!-- 聊天记录item -->
				<view class="chat-item" v-for="(item,index) in msg" :key="item.id" :id="'msg' + item.id">
					<!-- 时间  -->
					<view class="time" v-if="item.is_withdrawn === 0">{{timeShowFormat(item.send_time)}}</view>
					<!--a - 自己的信息-->
					<view class="content-wrapper-right" v-if= "item.if_see">
						<!-- 头像 -->
						<image :src="item.file_path" class="avator-avator-right"></image>
						<div style="width: 284px;float: right;">
							<!-- text - 文字 -->
							<view class="chat-content-right" v-if="item.message_type === 'text'">{{item.content}}</view>
							<!-- image - 图片 -->
							<view class="chat-image-right" v-if="item.message_type === 'image'">{{item.content}}</view>
							<!-- audio - 语音 -->
							<view class="chat-voice-right" v-if="item.message_type === 'audio'">{{item.content}}</view>
						</div>
					</view>
					<!-- b - 对方的消息  -->
					<view class="content-wrapper-left" v-if= "!item.if_see">
						<!-- 头像 -->
						<image :src="item.file_path" class="avator-avator-left"></image>
						<div style="width: 284px;float: left;">
							<!-- text - 文字 -->
							<view class="chat-content-left" v-if="item.message_type === 'text'">{{item.content}}</view>
							<!-- image - 图片 -->
							<view class="chat-image-left" v-if="item.message_type === 'image'">{{item.content}}</view>
							<!-- audio - 语音 -->
							<view class="chat-voice-left" v-if="item.message_type === 'audio'">{{item.content}}</view>
						</div>
					</view>
				</view>
			</scroll-view>	
		</div>
		<!--底部-->
		<div class="div2">
			<view style="width: 50px;height: 50px;float: left;">
				<u-icon name="mic" size="32px" style="margin-left: 20px;margin-top: 2px;"></u-icon>
			</view>
			<view style="margin-left: 15px;width: 260px;height: 25px;float: left;">
				<u--input
					shape="circle"
					placeholder="请输入内容"
					border="surround"
					v-model="value"
					clearable
					style="background-color: white;width: 230px;height: 25px;float: left;border-radius: 10px;"
				  ></u--input>
			</view>
			<view>
				<u-button style="width: 70px;height: 40px;background-color: #95ec69;font-size: 18px;border-radius: 10px;"  @click="sendMessage">发送</u-button>
			</view>
			<view style="width: 100%;height: 40px;margin-top: 10px;">
				<u-image src="../../static/icon/emoji.png" width="30px" height="30px" style="float: left;margin-left: 60px;"></u-image >
				<u-image src="../../static/icon/image.png" width="30px" height="30px" style="float: left;margin-left: 60px;"></u-image >
				<u-image src="../../static/icon/video.png" width="30px" height="30px" style="float: left;margin-left: 60px;"></u-image >
				<u-image src="../../static/icon/file.png" width="30px" height="30px" style="float: left;margin-left: 60px;"></u-image >
			</view>
		</div>
	</view>
</template>

<script>
	import timeUtil from '@/util/timeUtil.js';
    export default {
        data() {
            return {
				friendId: '', // 联系人id
				notation: '', // 联系人名称
				myId: '', // 用户id
				msg: [], // 聊天记录
				value:'' ,// 键盘输入的值
				id: '',
				lt:{
				 "persons":"",
				 "msg":"",
				 "sender":"",
				},
				ws:'',
				scrollToView: "",
				arrMsg: [],
				senderImgUrl: '',
				personsImgUrl: ''
			}
        },
		// 接收上个页面传递的参数
		onLoad: function (option) { 
			//option为object类型，会序列化上个页面传递的参数
			//打印出上个页面传递的参数。传递的是id=1，则获取到的就是option.id
			this.friendId = option.id;
			this.notation = option.notation;
			this.myId = option.myId;
			console.log(this.friendId);
			console.log(this.notation);
			console.log(this.myId);
		},
		//离开页面的操作
		destroyed () {
			this.beforeDestroy();
		},
		// 挂载
		mounted () {
			this.emptyUnRead();
			this.connect();
		},
		methods: {
			// 关闭连接
			beforeDestroy () {
			    if (!this.ws) {
			      this.ws.onclose();
			    }
			},
			saveMessageRecord(){ // 保存聊天记录
				uni.request({
					method:'POST',
				    url: 'http://localhost:8090/news/message/saveMessageRecord',
					// header: {'content-type': 'application/json; charset=UTF-8',},
				    data:  this.lt,
				    success: (res) => {
				        console.log(res.data.object);
				    }
				});
			},
			sendMessage () {
			    // 发送消息的json对象
			    this.lt.sender = this.myId
			    this.lt.persons = this.friendId
			    this.lt.msg = this.value
			    // 将json对象转为string发送给服务器
			    this.ws.send(JSON.stringify(this.lt))
				this.saveMessageRecord()
			    let arr = []
			    // 判断session中有没有聊天记录，有的话就拿出来
			    if (window.sessionStorage.getItem(this.friendId)) {
			        arr = JSON.parse(window.sessionStorage.getItem(this.friendId))
			    }
			    // 拼接当前聊天文本
			    const obj = {}
			    obj.content = this.lt.msg
				obj.if_see = true
				obj.message_type = "text"
				obj.file_path = this.senderImgUrl
				obj.sender_id = this.lt.sender
				obj.receiver_id = this.lt.persons
				obj.is_withdrawn = "1"
			    arr.push(obj)
				this.lt.msg = ''
				this.value = ''
			    // 将最新聊天文本存储到session中
			    window.sessionStorage.setItem(this.friendId, JSON.stringify(arr))
			    // 取出聊天记录，供页面展示
				console.log(JSON.parse(window.sessionStorage.getItem(this.friendId)))
				JSON.parse(window.sessionStorage.getItem(this.friendId))
				this.arrMsg = JSON.parse(window.sessionStorage.getItem(this.friendId));
				this.msg = this.msg.concat(this.arrMsg[(this.arrMsg.length - 1)])
				console.log(this.msg)
				this.$nextTick(function(){
					this.scrollToView = 'msg' + this.msg[(this.msg.length - 1)].id;
				});
			},
			// // 发送消息
			// sendMessage(){
			//   if (this.value === null) {
			// 	alert("请输入内容")
			//   } else {
			// 	if (typeof (WebSocket) == "undefined") {
			// 	  console.log("您的浏览器不支持WebSocket");
			// 	} else {
			// 	  console.log("您的浏览器支持WebSocket");
			// 	  this.lt.sender = this.myId
			// 	  this.lt.persons = this.friendId
			// 	  this.lt.msg = this.value
			// 	  this.ws.send(JSON.stringify(this.lt))
			// 	  this.readMessage()
			// 	  this.value = ''
			// 	  window.location.reload();
			// 	}
			//   }
			// },
			// 连接WebSocket
			connect () {
				this.readMessage();
				this.ws = new WebSocket('ws://localhost:8004/news/webSocket/' + this.myId)
				console.log(this.ws)
				this.ws.onopen = this.websocketonopen
				this.ws.onmessage = this.websocketonmessage
				// this.ws.onerror = this.websocketonerror
				// this.ws.onclose = this.websocketclose
				// this.ws.onmessage = function (a) {
					
				//   const value = a.data
				//   console.log(value)
				//   console.log(11111)
				// }
			},
			websocketonopen () {
				console.log('我进来了')
			},
			websocketonmessage (res) {
				// 接收系统推送的消息
				const dataStr = res.data
				// 将dataStr转承JSON对象
				const objcet = JSON.parse(dataStr)
				// 不是系统消息
				// 判断是不是发送给当前用户的
				// 拼接接收方聊天文本
				// 不同的发送者将存储到不同的session中
				// 在拼接聊天文本前 判断session中是否有聊天消息
				// 有的话就取出来 + 新拼接的一条拼成一条最新的聊天记录，并存储到session中
				if (this.myId === objcet.persons) {
					let arr = []
					if (window.sessionStorage.getItem(objcet.sender)) {
						arr = JSON.parse(window.sessionStorage.getItem(objcet.sender))
					}
					const obj = {}
					obj.content = objcet.msg
					obj.if_see = false
					obj.message_type = "text"
					obj.file_path = this.personsImgUrl
					obj.sender_id = this.lt.persons
					obj.receiver_id = this.lt.sender
					obj.is_withdrawn = "1"
					arr.push(obj)
					// obj.time = time(new Date().getTime(), 'YYYY-MM-DD hh:mm:ss')
					window.sessionStorage.setItem(objcet.sender, JSON.stringify(arr))
					if (this.friendId !== '') {
						JSON.parse(window.sessionStorage.getItem(this.friendId))
						this.arrMsg = JSON.parse(window.sessionStorage.getItem(this.friendId));
						this.msg = this.msg.concat(this.arrMsg[(this.arrMsg.length - 1)])
						console.log(this.msg)
					}
					this.$nextTick(function(){
						this.scrollToView = 'msg' + this.msg[(this.msg.length - 1)].id;
					});
				}
			},
			websocketonerror (res) {
			  console.log('我出错了' + res)
			},
			websocketclose (res) {
			  this.ws.close()
			  window.sessionStorage.removeItem('userName')
			  this.$router.push('/')
			},
			// 聊天记录
			readMessage () {
				uni.request({
					url: 'http://localhost:8090/news/friend/friendById',
					method: 'get',
					dataType: 'json',
					data:{
						myId: this.myId,
						friendId: this.friendId
					},
					success: (res) => {
						if (res.data.flag) {
							this.id = res.data.object.myId
						}
					}
				})
				uni.request({
					url: 'http://localhost:8090/news/message/readMessage',
					method: 'get',
					dataType: 'json',
					data:{
						myId: this.myId,
						friendId: this.friendId
					},
					success: (res) => {
						if (res.data.flag) {
							this.msg = res.data.object
							for(let i = 0; i < this.msg.length; i++){
								if (this.msg[i].sender_id === this.id) {
									this.msg[i].if_see = true
									this.senderImgUrl = this.msg[i].file_path
								} else {
									this.personsImgUrl = this.msg[i].file_path
								}
							}
							this.$nextTick(function(){
								this.scrollToView = 'msg' + this.msg[(this.msg.length - 1)].id;
							});
							console.log(this.msg)
						}
					}
				})
			},
			// 跳转页面
			returnHot () {
				uni.switchTab({
					url: '/pages/hot/hot',
				})
				this.beforeDestroy();
				window.location.reload();
			},
			//清空未读消息
			emptyUnRead () {
				uni.request({
					url: 'http://localhost:8090/news/friend/emptyUnRead',
					method: 'get',
					dataType: 'json',
					data:{
						myId: this.myId,
						friendId: this.friendId
					},
					success: (res) => {
						if (res.data.flag) {
							console.log(res.data.object)
						} else {
							console.log(res.data.object)
						}
					}
				})
			},
			// 转换时间
			timeShowFormat(time){
				// console.log(Number(time));
				// console.log(timeUtil.getFormatTime(Number(time)));
				// console.log(timeUtil.timeShowFormat(time));
				// return timeUtil.timeShowFormat(timeUtil.getFormatTime(Number(time)));
				return timeUtil.timeShowFormat(time);
			},
		}
    }
</script>

<style>
	.div1{
		width: 100%;
		height: 732px;
		bottom: 0;
		width: 100%;
		background-color: #ececec;
		/* background-color: gold; */
		position: fixed;
		top: 54px;
		overflow: scroll;
		padding-bottom: 20px;
		overflow-y: auto;
	}
	.div2{
		width: 100%;
		height: 80px;
		position: fixed;
		padding-top: 10px;
		bottom: 0;
		width: 100%;
		background-color: #f9f9f9;
	}
	.chat-item{
		font-size: 15px;
		color: #000000;
	}
	.time{
		width: 100%;
		height: 18px;
		color: #000000;
		margin-left: auto;
		margin-right: auto;
		text-align: center;
		font-size: 13px;
		margin-top: 10px;
		z-index: 2;
		
	}
	.content-wrapper-left{
		display: flow-root;
		padding: 10px 10px 0 10px;
	}
	.avator-avator-left{
		width: 50px;
		height: 50px;
		border-radius: 50%;
		border: #fff solid 1px;
		float: left;
	}
	.chat-content-left{
		float: left;
		background-color: #fff;
		margin-left: 6px;
		padding: 4px 10px;
		border-radius: 6px;
		margin-top: 8px;
		line-height: 28px;
	}
	.content-wrapper-right{
		display: flow-root;
		padding: 10px 10px 0 10px;
	}
	.chat-content-right{
		float: right;
		background-color: #95ec69;
		margin-right: 6px;
		padding: 4px 10px;
		border-radius: 6px;
		margin-top: 8px;
		line-height: 28px;
	}
	.avator-avator-right{
		width: 50px;
		height: 50px;
		border-radius: 50%;
		border: #fff solid 1px;
		float: right;
	}
	.chat-main{
		width: 100%;
		height: 732px;
	}
</style>